package com.woniuxy.micromedicalserver.websocket.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.micromedicalserver.bean.WebSocketMsg;
import com.woniuxy.micromedicalserver.configuration.HttpSessionConfiguration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat", configurator = HttpSessionConfiguration.class)
@Component
public class ChatRoomEndpoint {

    private static Map<String, ChatRoomEndpoint> onlineUsers = new ConcurrentHashMap<>();
    private Session session;
    private HttpSession httpSession;



    @OnOpen
    public void onOpen(Session session, EndpointConfig endpointConfig) throws JsonProcessingException {
        this.session = session;
        this.httpSession = (HttpSession) endpointConfig.getUserProperties().get(HttpSession.class.getName());

        String userName = (String) httpSession.getAttribute("user");
        onlineUsers.put(userName, this);

        String id = this.httpSession.getId();
        System.out.println(id);
        System.out.println(userName);

        //-----------------------------接下来初始化------------------------------------

        WebSocketMsg msg = new WebSocketMsg();
        msg.setSysMsg(true);
        msg.setContent(onlineUsers.keySet());

        String jsonMsg = new ObjectMapper().writeValueAsString(msg);
        broadcastAllUsers(jsonMsg);


    }

    @OnClose
    public void onClose(Session session){

    }



    @OnMessage
    public void onMessage(Session session, String message) throws IOException {

        WebSocketMsg msg = new ObjectMapper().readValue(message, WebSocketMsg.class);
        //System.out.println(msg);
        System.out.println(message);
        String toName = msg.getToName();
        onlineUsers.get(toName).session.getBasicRemote().sendText(message);







    }


    private Set<String> getNames(){
        return onlineUsers.keySet();
    }


    //总算觉得写了一段像样的代码，呆！
    private void broadcastAllUsers(String msg){

        onlineUsers.keySet().forEach(
                e -> {
                    try {
                        onlineUsers.get(e).session.getBasicRemote().sendText(msg);
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
        );

    }


}
